import {createRouter, createWebHistory} from "vue-router";
import {routeData} from "@/config";
import {setLocalStorage} from "@/utils";
import {StorageEnum} from "@/enums/storageEnum";

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: routeData,
});

router.beforeEach((to, _from, next) => {
    window.$loadingBar?.start();
    if (to.name == "login") {
        if (sessionStorage.getItem(StorageEnum.IS_AUTHENTICATED)?.toUpperCase() == "TRUE") {
            next({name: "index"});
        } else {
            next();
        }
    } else {
        if (sessionStorage.getItem(StorageEnum.IS_AUTHENTICATED)?.toUpperCase() == "TRUE") {
            sessionStorage.setItem(StorageEnum.CURRENT_ROUTE, <string>to.name || "index");
            next();
        } else {
            next({name: "login"});
        }
    }
});
router.afterEach((to) => {
    setLocalStorage(StorageEnum.CURRENT_ROUTE, to.name)
    window.$loadingBar?.finish();
});

export default router;
